<?php

namespace app\home\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Session;

class Forum
{
    //交流列表
    public function forum()
    {
        $type = input('type','all');
        if(request()->isAjax()){
            $where = [];
            if($type!='all'){
                //交流类型分为：bug=>bug或建议 update=>更新内容
                $where[] = ['type','=',$type];
            }
            $page = (int)input('page', 1);
            $page =  (int)$page;
            $limit = input('limit', 10);
            
            // 获取总数
            $total = Db::name('forum')->where($where)->count();
            
            // 获取列表数据
            $forum_list = Db::name('forum')
                ->where($where)
                ->order('id', 'desc')
                ->page($page, $limit)
                ->select()
                ->toArray();
            
            // 获取用户信息和回复数
            foreach($forum_list as &$item){
                $user = Db::name('users')->where('user_id', $item['user_id'])->find();
                if(!$user){
                    $user = [
                        'nickname' => '匿名',
                        'head_pic' => getCurUrl().'/static/design_page/poster/default-avatar.png',
                    ];
                }
                $item['user'] = $user;
                $item['reply_count'] = Db::name('forum_reply')->where('forum_id', $item['id'])->count();
            }
            
            return json([
                'status' => 1,
                'msg' => '查询成功', 
                'data' => [
                    'data' => $forum_list,
                    'total' => $total
                ]
            ]);
        }

        View::assign('type',$type);

        return View::fetch();
    }
    
    //交流详情
    public function forum_detail()
    {
        $id = input('id');
        if(!$id){
            return json(['status' => 0, 'msg' => '参数错误']);
        }

        // 获取帖子详情
        $forum = Db::name('forum')->where('id', $id)->find();
        if(!$forum){
            return json(['status' => 0, 'msg' => '帖子不存在']);
        }

        // 更新浏览量
        Db::name('forum')->where('id', $id)->inc('view_count')->update();

        // 获取用户信息
        $user = Db::name('users')->where('user_id', $forum['user_id'])->find();
        if(!$user){
            $user = [
                'nickname' => '匿名',
                'head_pic' => getCurUrl().'/static/design_page/poster/default-avatar.png',
            ];
        }
        $forum['user'] = $user;

        // 获取回复列表
        $replies = Db::name('forum_reply')
            ->where('forum_id', $id)
            ->order('id', 'asc')
            ->select()
            ->toArray();

        // 获取回复用户信息
        foreach($replies as &$reply){
            $reply_user = Db::name('user')->where('id', $reply['user_id'])->find();
            $reply_avatar = Db::name('file')->where('id', $reply_user['avatar'])->find();
            $reply_user['avatar_file'] = $reply_avatar ?: ['path' => '/static/admin/images/avatar.jpg'];
            $reply['user'] = $reply_user;
        }

        $forum['replies'] = $replies;
        $forum['reply_count'] = count($replies);

        View::assign('forum', $forum);

        
        return View::fetch();
    }

    //添加交流信息
    public function forum_add()
    {
        if(request()->isAjax()){
            $data = input('post.');
            
            // 验证数据
            if(empty($data['title']) || empty($data['content']) || empty($data['type'])){
                return json(['code' => 1, 'msg' => '请填写完整信息']);
            }
            
            // 获取当前用户ID
//            $user = json_decode(localStorage('user'), true);
//            if(!$user || !isset($user['id'])){
//                //return json(['code' => 1, 'msg' => '请先登录']);
//            }
            
            // 组装数据
            $insert_data = [
                'title' => $data['title'],
                'content' => $data['content'],
                'type' => $data['type'],
                'user_id' => $user['id']??'',
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'view_count' => 0
            ];
            
            // 插入数据
            $result = Db::name('forum')->insert($insert_data);
            if($result){
                return json(['status' => 0, 'msg' => '发布成功']);
            }else{
                return json(['status' => 1, 'msg' => '发布失败']);
            }
        }
        
        return View::fetch();
    }
    
    //回复帖子
    public function reply()
    {
        if(!request()->isAjax()){
            return json(['code' => 1, 'msg' => '非法请求']);
        }
        
        $data = input('post.');
        
        // 验证数据
        if(empty($data['content']) || empty($data['forum_id'])){
            return json(['code' => 1, 'msg' => '请填写回复内容']);
        }
        
        // 获取当前用户ID
        $user = json_decode(localStorage('user'), true);
        if(!$user || !isset($user['id'])){
            return json(['code' => 1, 'msg' => '请先登录']);
        }
        
        // 组装数据
        $insert_data = [
            'forum_id' => $data['forum_id'],
            'content' => $data['content'],
            'user_id' => $user['id'],
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        // 插入数据
        $result = Db::name('forum_reply')->insert($insert_data);
        if($result){
            return json(['code' => 0, 'msg' => '回复成功']);
        }else{
            return json(['code' => 1, 'msg' => '回复失败']);
        }
    }
    
    // 获取用户信息辅助函数
    private function localStorage($key)
    {
        return isset($_COOKIE[$key]) ? $_COOKIE[$key] : '';
    }
}
